const Router = require('koa-router')
const Client = require('../schema/Client')

const clientRouter = new Router({
  prefix: '/nodeApi/client'
})

clientRouter.get('/admin/findByPage', async ctx => {
  let query = {};
  // let brand = ctx.query.brand;
  let opName = ctx.query.opName;
  let opCode = ctx.query.opCode;
  // let title = ctx.query.title;
  let page = ctx.query.page;
  let limit = ctx.query.limit;
  let sort = '-generateTime';
  if (page && limit) {
    // if (brand) {
    //   query.brand = brand;
    // }
    if (opCode) {
      query.opCode = opCode;
    }
    if (opName) {
      query.opName = {
        $regex: new RegExp(opName)
      }
    }
    // if (title) {
    //   query.title = {
    //     $regex: new RegExp(title, 'i')
    //   }
    // }
    if (ctx.query.sort) {
      sort = ctx.query.sort
    }
    let clients = await Client.paginate(query, { page, limit, sort });
    ctx.body = clients;
  } else {
    ctx.status = 400;
    ctx.body = {
      result: 'fail'
    }
  }
})

clientRouter.delete('/admin/remove', async ctx => {
  let opCode = ctx.request.body
  if (opCode) {
    await Client.deleteMany({ opCode })
    ctx.body = {
      result: 'success'
    }
  } else {
    ctx.status = 400;
    ctx.body = {
      result: 'fail'
    }
  }
})

clientRouter.patch('/admin/update/:opCode', async ctx => {
  let opCode = ctx.params.opCode
  let body = ctx.request.body
  let client = await Client.findOne({ opCode })
  delete body.__v
  client.set(body)
  await client.save()
  ctx.body = {
    result: 'success'
  }
})

clientRouter.post('/admin/new', async ctx => {
  let client = ctx.request.body
  await new Client(client).save()
  ctx.body = {
    result: 'success'
  }
})

module.exports = clientRouter